from FunctionDemo import Caculator
import pytest
import yaml
import allure
import logging
# allure生成测试报告需要2步，
# 1：收集测试用例到报告指定路径，pytest --alluredir = '报告路径'，2：打开测试报告 allure serve '报告路径'
# 读取yaml文件测试数据
def get_data(datatype):
    with open('./testdata_cal.yaml', encoding='utf-8') as f:
        cal_data = yaml.safe_load(f)[datatype]
        # datas = cal_data['datas']
        # dataids = cal_data['dataids']
    
    return cal_data

# 日志设置
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()


# 计算器自动化测试类
class TestCaculator():

    # 测试加法功能
    # 测试数据参数化
    @allure.feature('加法功能模块')
    @pytest.mark.parametrize('num1, num2, expect', get_data('add')['datas'], ids=get_data('add')['dataids'])
    def test_add(self, num1, num2, expect, get_cal):
        result = get_cal.num_add(num1, num2)
        # 计算结果为浮点数，特殊处理：保留2位小数
        if isinstance(result, float):
            result = round(result, 2)
        # 断言
        try:
            assert result == expect
        except AssertionError:
            logger.error('断言失败，测试实际结果与预期不相符')
            
        
        # 添加日志打印
        logger.info(f'{num1}+{num2}={result}')


    # 测试减法功能,先跳过执行
    @allure.feature('减法功能模块（暂未实现）')
    def test_sub(self, num1, num2, expect):
        # pass
        logger.error('乘法功能未实现…………')
    

    # 测试乘法功能
    @allure.feature('乘法功能模块（暂未实现）')
    def test_mul(self, num1, num2, expect):
        # pass
        logger.error('乘法功能未实现…………')

    # 测试除法功能
    @allure.feature('除法功能模块')
    @pytest.mark.parametrize('num1, num2, expect', get_data('div')['datas'], ids=get_data('div')['dataids'])
    def test_div(self, num1, num2, expect, get_cal):
        result = get_cal.num_div(num1, num2)
        # 计算结果为浮点数，特殊处理：保留2位小数
        if isinstance(result, float):
            result = round(result, 2)
        # 断言
        try:
            assert result == expect
        except AssertionError:
            logger.error('断言失败，测试实际结果与预期不相符')
        logger.info(f'{num1}/{num2}={result}')



